<template>
  <div class="table-style">
    <avue-crud
    class="table"
      :data="dataList"
      :option="option"
      :page.sync="page"
      :key="key"
      @row-update="rowUpdate"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="resetChange"
      @size-change="sizeChange"
      @current-change="currentChange"
      @refresh-change="refreshChange"
    >
      <!-- 搜索表单 ---- 自定义按钮 -->
      <template slot="searchMenu">
        <slot name="searchBtn" />
      </template>
      <!-- 搜索表单 ---- 自定义搜索内容 -->
      <template slot="search">
        <slot name="searchContent" />
      </template>
      <!-- 左侧菜单栏 -->
      <template slot="menuLeft" slot-scope="{ size }">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="onAddOrUpdateBtn('new')"
          v-if="option.customizeAddBtn"
          >新增</el-button
        >
        <span class="manu-left" v-if="option.sortable">
          <span class="label">选择分组的列:</span>
          <el-select
            @change="onChangeSelct"
            v-model="selectVal"
            clearable
            :size="size"
            class="w_200"
          >
            <el-option
              v-for="item in copyColumns"
              :key="item.prop"
              :label="item.label"
              :value="item.prop"
            >
            </el-option>
          </el-select>
        </span>
        <slot name="menuLeft" />
      </template>
      <!-- 右侧菜单栏 -->
      <template slot="menuRight" slot-scope="{ size }">
        <!-- <el-button
          icon="el-icon-printer"
          circle
          :size="size"
          @click="onPrintBtn"
          v-if="printBtn"
        ></el-button>
        <slot name="menuRight" /> -->
      </template>
      <!-- 自定义操作栏 -->
      <template slot-scope="{ type, size, row }" slot="menu">
        <!-- 查看 -->
        <el-button
          type="text"
          icon="el-icon-view"
          :size="size"
          @click="onAddOrUpdateBtn('view', row)"
          v-if="option.customizeViewBtn"
          >查看</el-button
        >
        <!-- 修改 -->
        <el-button
          type="text"
          icon="el-icon-edit"
          :size="size"
          @click="onAddOrUpdateBtn('update', row)"
          v-if="option.customizeEditBtn"
          >修改</el-button
        >
        <slot name="action"></slot>
      </template>
    </avue-crud>
    <print ref="print" :column="option.column" :dataList="dataList"> </print>
  </div>
</template>

<script>
import print from "@/components/print/index.vue";
import options from "./options.js";
export default {
  components: { print },
  props: {
    // 表格数据和条数
    data: {
      type: Object,
      default: () => {
        return {};
      },
    },
    // 配置项
    config: {
      type: Object,
      default: () => {
        return {
          column: [
            // {
            //   label: "编号",
            //   prop: "number",
            //   // search: true, // 表示该列既是表格列,又是搜索列
            // },
          ],
        };
      },
    },
    pageParams: {
      type: Object,
      default: () => {
        return {
          background: false, // 分页是否需要背景色
          pageSize: 10,
          pagerCount: 5,
          currentPage: 1,
        };
      },
    },
  },
  data() {
    return {
      printBtn: false, // 是否显示自定义打印
      key: 1,
      dataList: [], // 表格展示数据
      copyDataList: [], // 初始化的表格的备份
      currentDataList: [], // 更改后的表格所有数据的备份
      copyColumns: [], // 初始化的表格列的备份
      selectVal: "", // 分组框框
      search: {}, // 搜索表单
      page: {
        background: false, // 分页是否需要背景色
        pageSize: 10,
        pagerCount: 5,
        currentPage: 1,
      },
      option: {
        rowKey: "id",
        rowParentKey: "parentId",
        index: true, // 是否有序号
        selection: true, // 是否有多选
        searchIcon: true, //是否启用搜索功能按钮
        headerAlign: "center", // 表头居中
        align: "center", // 内容居中
        showPage: true, // 是否显示分页
        highlightCurrentRow: true, // 是否要高亮当前行
        column: [],
      },
    };
  },
  watch: {
    ["option.column"]: {
      deep: true,
      immediate: true,
      handler(v) {
        if (v && v.length > 0) {
          let label = v[0].prop;
          this.currentProp = label;
          if (this.copyDataList.length > 0) {
            if (this.option.dragGroup) {
              this.page.currentPage = 1;
              this.page.pageSize = this.pageParams
                ? this.pageParams.pageSize
                : 10;
              this.currentDataList = this.treeListHandle(label);
            }
            if (this.option.showPage) {
              this.paging();
            } else {
              this.dataList = this.copyDataList;
            }
            this.key++;
          }
        }
      },
    },
    data: {
      deep: true,
      immediate: true,
      handler(v) {
        if (v.list && v.list.length > 0) {
          this.copyDataList = this.deepClone(v.list);
          if (this.option.dragGroup) {
            this.currentDataList = this.treeListHandle(this.currentProp);
          } else {
            this.currentDataList = v.list;
          }
          if (this.option.showPage) {
            this.paging();
          } else {
            this.dataList = this.copyDataList;
          }
          this.key++;
        }
      },
    },
  },
  created() {
    this.init();
  },
  methods: {
    onPrintBtn() {
      this.$refs.print.printDialogVisible = true;
    },
    // 初始化加载数据和表格
    init() {
      // 初始化列
      this.printBtn = this.config.printBtn;
      this.option = {
        ...options(this), // 所有属性都设置
        // ...this.option,
        ...this.config,
        // printBtn: false,
      };
      // 将原本的列，及备份
      this.copyColumns =
        this.option.column.length > 0 ? this.deepClone(this.option.column) : [];
      // 分页参数的配置
      if (this.option.showPage) {
        this.page = {
          background: false,
          pageSize: 10,
          pagerCount: 5,
          currentPage: 1,
          ...this.pageParams,
        };
      }
    },
    // 分页
    paging() {
      let currentPage = this.page.currentPage;
      let pageSize = this.page.pageSize;
      let start = (currentPage - 1) * pageSize;
      let list = this.deepClone(this.currentDataList);
      this.page.total = this.currentDataList.length;
      this.dataList = list.splice(start, pageSize);
    },
    // 选择框修改需要分组的列
    onChangeSelct() {
      if (this.selectVal) {
        let columns = this.deepClone(this.option.column);
        let arr = columns.filter((item) => {
          return item.prop === this.selectVal;
        });
        if (!arr.length) return;
        let obj = arr[0];
        columns.splice(columns.indexOf(obj), 1);
        columns.unshift(obj);
        this.$set(this.option, "column", columns);
      } else {
        this.$set(this.option, "column", this.copyColumns);
      }
    },
    /**
     * 将普通数组转化为树形结构的树
     * @param {操作的表格} list
     * @param {需要分组的列的prop值} label
     */
    treeListHandle(label) {
      let tempArr = this.deepClone(this.copyDataList);
      if (this.copyDataList.length > 0) {
        this.copyDataList.map((item) => {
          tempArr.map((child) => {
            if (item[label] === child[label] && !child.parentId) {
              this.$set(child, "parentId", item.id);
              if (child.id === item.id) {
                this.$set(child, "parentId", "0000-0000-0000");
              }
            }
          });
        });
      }
      let arr = this.handleTree(tempArr);
      return arr;
    },
    // 表格点击删除
    rowDel(row, index, done) {
      // done(row);
      this.$emit("rowDel", row, index, done);
    },
    /**
     * 自定义新增按钮
     */
    onAddOrUpdateBtn(type, data) {
      this.$emit("onActionBtn", type, data);
    },
    // 弹窗点击保存 ---- 新增的保存
    rowSave(row, done) {
      row.parentId = this.parentId;
      row.id = new Date().getTime();
      this.parentId = undefined;
      // done(row);
      setTimeout(() => {
        done();
      }, 3000);
      this.$emit("rowSave", row, done);
    },
    // 弹窗点击保存 ---- 修改的保存
    rowUpdate(row, index, done) {
      // done(row);
      setTimeout(() => {
        done();
      }, 3000);
      this.$emit("rowUpdate", row, index, done);
    },
    // 点击清空按钮
    resetChange(item) {
      this.$emit("refreshDataList");
    },
    // 点击搜索后执行方法，done方法为关闭等待框
    searchChange(params, done) {
      setTimeout(() => {
        done();
        this.$message.success(JSON.stringify(params));
      }, 3000);
      this.$emit("searchChange", params, done);
    },
    /**
     * 修改当前页数
     * @param {当前页数} page
     */
    currentChange(val) {
      this.page.currentPage = val;
      this.paging();
      this.$emit("currentChange", val);
    },
    /**
     * 修改每页条数
     * @param {每页条数} size
     */
    sizeChange(val) {
      this.page.currentPage = 1;
      this.page.pageSize = val;
      this.paging();
      this.$emit("sizeChange", val);
    },
    /**
     * 刷新事件, 将表格恢复成原来的样子
     */
    refreshChange() {
      this.search = {};
      this.page.currentPage = 1;
      this.page.pageSize = this.pageParams ? this.pageParams.pageSize : 10;
      this.selectVal = "";
      this.onChangeSelct();
    },
  },
};
</script>

<style lang="scss" scoped>
.table-style {
  .manu-left {
    display: flex;
    align-items: center;
    .label {
      display: block;
      font-size: 12px;
      min-width: 90px;
    }
  }
  ::v-deep .avue-crud__left {
    display: flex;
    text-align: center;
    align-items: center;
    width: 50%;
  }
  ::v-deep .avue-form__menu--center {
    text-align: end;
  }
}
</style>